
import {isIOS} from '@/util/utils'
function CompassImg(dataURL, callback, shouldCompress = true) {
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    //    瓦片canvas
    var tCanvas = document.createElement("canvas");
    var tctx = tCanvas.getContext("2d");
    const img = new window.Image();
    img.src = dataURL;
    var initSize = img.src.length;
    img.onload = async () => {
        //获取图片方向
        //只在ios会出现图片翻转的问题 安卓objectURLToBlob方法中有bug
        var orient=isIOS()?await getOrientation(img):1;
        var width = img.width;
        var height = img.height;
        // 在IOS中，canvas绘制图片是有两个限制的：
        //首先是图片的大小，如果图片的大小超过两百万像素，
        //图片也是无法绘制到canvas上的，调用drawImage的时候不会报错，但是你用toDataURL获取图片数据的时候获取到的是空的图片数据。
        //再者就是canvas的大小有限制，如果canvas的大小大于大概五百万像素（即宽高乘积）的时候，不仅图片画不出来，其他什么东西也都是画不出来的。
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        // 如果是png转jpg，绘制到canvas上的时候，canvas存在透明区域的话，当转成jpg的时候透明区域会变成黑色
        // 因为canvas的透明像素默认为rgba(0,0,0,0)，所以转成jpg就变成rgba(0,0,0,1)了，
        // 也就是透明背景会变成了黑色。解决办法就是绘制之前在canvas上铺一层白色的底色。
        var ratio;
        if ((ratio = (width * height) / 4000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        //这里做了最大的压缩图片尺寸限制 1000*1000 太大canvas压缩会失败 可以用瓦片绘制
        // if(width>1000){width=1000}
        // if(height>1000){height=1000}
        canvas.width = width;
        canvas.height = height;

        //铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        //如果图片像素大于100万则使用瓦片绘制
        var count;
        console.log(width, height);
        if ((count = (width * height) / 2000000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片

            //计算每块瓦片的宽和高
            var nw = ~~(width / count);
            var nh = ~~(height / count);

            tCanvas.width = nw;
            tCanvas.height = nh;

            for (var i = 0; i < count; i++) {
                for (var j = 0; j < count; j++) {
                    tctx.drawImage(
                        img,
                        i * nw * ratio,
                        j * nh * ratio,
                        nw * ratio,
                        nh * ratio,
                        0,
                        0,
                        nw,
                        nh
                    );
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }
        if (orient != "" && orient != 1) {
            switch (Number(orient)) {
                case 6: //需要顺时针（向左）90度旋转
                    rotateImg(img, "left", canvas);
                    break;
                case 8: //需要逆时针（向右）90度旋转
                    rotateImg(img, "right", canvas);
                    break;
                case 3: //需要180度旋转
                    rotateImg(img, "right", canvas); //转两次
                    rotateImg(img, "right", canvas);
                    break;
                default : break;
            }
        }
        //进行最小压缩
        let data = {};
        let compressedDataUrl;
        //注意这里 canvas.toDataURL对png类型无效 所以要先转成jpg
        if (shouldCompress) {
            compressedDataUrl = canvas.toDataURL("image/jpeg", 0.3);
        } else {
            compressedDataUrl = canvas.toDataURL("image/jpeg");
        }

        console.log("压缩前：" + initSize);
        console.log("压缩后：" + compressedDataUrl.length);
        console.log("压缩率：" +~~((100 * (initSize - compressedDataUrl.length)) / initSize) +"%");

        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        data.compressedDataUrl = compressedDataUrl;
        callback(data.compressedDataUrl);
    };
}

function getOrientation(img, callback) {
    var reader = new window.FileReader();
    return new Promise(resolve=>{
        reader.onload = function (e) {  
            var view = new window.DataView(e.target.result);
            if (view.getUint16(0, false) != 0xffd8) {
                return resolve(-2);
            }
            var length = view.byteLength,
                offset = 2;
            while (offset < length) {
                var marker = view.getUint16(offset, false);
                offset += 2;
                if (marker == 0xffe1) {
                    if (view.getUint32((offset += 2), false) != 0x45786966) {
                        return resolve(-1);
                    }
                    var little = view.getUint16((offset += 6), false) == 0x4949;
                    offset += view.getUint32(offset + 4, little);
                    var tags = view.getUint16(offset, little);
                    offset += 2;
                    for (var i = 0; i < tags; i++) {
                        if (view.getUint16(offset + i * 12, little) == 0x0112) {
                            return resolve(view.getUint16(offset + i * 12 + 8, little));
                        }
                    }
                } else if ((marker & 0xff00) != 0xff00) {
                    break;
                } else {
                    offset += view.getUint16(offset, false);
                }
            }
            return resolve(-1);
        };
        objectURLToBlob(img.src, function (blob) {
            
            reader.readAsArrayBuffer(blob);
        });
    })
}

function rotateImg(img, direction, canvas) {
    //最小与最大旋转方向，图片旋转4次后回到原方向
    const min_step = 0;
    const max_step = 3;
    if (img == null) return;
    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
    let height = img.height;
    let width = img.width;
    let step = 2;
    if (step == null) {
        step = min_step;
    }
    if (direction == "right") {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
    } else {
        step--;
        step < min_step && (step = max_step);
    }
    //旋转角度以弧度值为参数
    let degree = (step * 90 * Math.PI) / 180;
    let ctx = canvas.getContext("2d");
    switch (step) {
        case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0);
            break;
        case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height);
            break;
        case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height);
            break;
        case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0);
            break;
        default : break;
    }
}

function objectURLToBlob(url, callback) {
    
    var http = new XMLHttpRequest();
    http.open("GET", url, true);
    http.responseType = "blob";
    http.onload = function(e) {
        if (this.status == 200 || this.status === 0) {
            callback(this.response);
        }
    };
    http.send();
}
export default CompassImg;